package com.yskj.mwk.utils;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yskj.mwk.controller.WxPayController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class WxShippingUtil {

    private static final Logger logger = LoggerFactory.getLogger(WxShippingUtil.class);

    public String uploadShipping(String access_token,String transaction_id,String is_all_delivered,String tracking_no,String orderDesc,String receiverTell,String openid) {
        boolean isAll=true;
        if (is_all_delivered.equals("false")){
            isAll=false;
        }
        String url="https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token="+access_token;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> order_key = new HashMap<>();
        order_key.put("order_number_type",2);
        order_key.put("transaction_id",transaction_id);
        map.put("order_key", order_key);
        map.put("logistics_type", 1);
        map.put("delivery_mode", 2);
        map.put("is_all_delivered", isAll);
        map.put("shipping_list", createShippingList(tracking_no, orderDesc, receiverTell));
        // 1. 获取东八区当前时间
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        // 2. 定义格式化模板（精确到毫秒+时区）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        // 3. 格式化输出
        String formattedTime = now.format(formatter);
        map.put("upload_time", formattedTime);
        Map<String, Object> payer = new HashMap<>();
        payer.put("openid", openid);
        map.put("payer", payer);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(map);
            logger.info("【微信物流提交信息】：{}",json);
            String result=HttpClientUtils.sendPostRequest(url, json);
            logger.info("【微信物流应答信息】：{}",result);
            ObjectMapper objectMapper2= new ObjectMapper();
            JsonNode rootNode = objectMapper2.readTree(result);
            JsonNode errmsgNode = rootNode.get("errmsg");
            return errmsgNode.asText();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private static List<Map<String, Object>> createShippingList(String tracking_no,String orderDesc,String receiverTell) {
        List<Map<String, Object>> shippingList = new ArrayList<>();

        // 第一个物流信息
        Map<String, Object> shippingItem = new LinkedHashMap<>(); // 保持插入顺序
        shippingItem.put("tracking_no", tracking_no);
        shippingItem.put("express_company", "JTSD");
        shippingItem.put("item_desc", orderDesc);
        // 嵌套联系人信息
        Map<String, String> contact = new HashMap<>();
        contact.put("receiver_contact", receiverTell);
        shippingItem.put("contact", contact);

        shippingList.add(shippingItem);

        return shippingList;
    }

    /**
     * 报备测试订单
     * */
    public String opspecialorder(String access_token,String transaction_id,String type) {
        String url="https://api.weixin.qq.com/wxa/sec/order/opspecialorder?access_token="+access_token;
        Map<String, Object> map = new HashMap<>();
        map.put("order_id", transaction_id);
        map.put("type", type);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String datetime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(datetime, formatter);
        map.put("delay_to", localDateTime.atZone(ZoneId.of("UTC")).toEpochSecond());
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(map);
            logger.info("【微信物流报备订单】请求参数：{}",json);
            String result=HttpClientUtils.sendPostRequest(url, json);
            logger.info("【微信物流报备订单】应答参数：{}",result);
            ObjectMapper objectMapper2= new ObjectMapper();
            JsonNode rootNode = objectMapper2.readTree(result);
            JsonNode errmsgNode = rootNode.get("errmsg");
            return errmsgNode.asText();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
